﻿#include "facerecvpic.h"
#include "oeasycommon.h"
#include <QFile>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

FaceRecvPic::FaceRecvPic(int recvPort, QString id, STRUCT_RECOG_INFO filter, QObject *parent) :
    QObject(parent),
    m_id(id),
    m_filter(filter),
    m_jpgServer()
{
    m_jpgServer.listen(QHostAddress::Any, recvPort);
    connect(&m_jpgServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}

FaceRecvPic::~FaceRecvPic()
{
    m_jpgServer.close();
}

void FaceRecvPic::onNewConnection()
{
    QTcpSocket *newSock = m_jpgServer.nextPendingConnection();

    DEBUG_PRINT << newSock->peerAddress();
    FaceRecvCli *newCli = new FaceRecvCli(newSock, m_id, m_filter);
    m_cliList.push_back(newCli);
    connect(newCli, SIGNAL(error()), this, SLOT(onCloseConnect()));
    connect(newCli, SIGNAL(textRecv(QString)), this, SIGNAL(textRecv(QString)));
}

void FaceRecvPic::onCloseConnect()
{
    FaceRecvCli *c = (FaceRecvCli*)this->sender();
    m_cliList.removeOne(c);
    c->deleteLater();
}

FaceRecvCli::FaceRecvCli(QTcpSocket *sock, QString id, STRUCT_RECOG_INFO face, QObject *parent) :
    QObject(parent),
    m_sock(sock),
    m_recog(id, face),
    m_recogTime(0)
{
    connect(m_sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));
    connect(m_sock, SIGNAL(readyRead()), this, SLOT(onRead()));
    connect(&m_recog, SIGNAL(postOver(QByteArray, QByteArray)), this, SLOT(onPostOver(QByteArray, QByteArray)));
}

FaceRecvCli::~FaceRecvCli()
{
    m_sock->close();
    m_sock->deleteLater();
    m_sock->disconnect();
    m_recog.disconnect();
}

void FaceRecvCli::onError(QAbstractSocket::SocketError err)
{
    WARNING_PRINT << m_sock->peerAddress() << err;
    emit error();
}

void FaceRecvCli::onRead()
{
    QByteArray recvBA = m_sock->readAll();
    int index = recvBA.indexOf(',');

    m_jpg.append(recvBA.mid(0, index));
    if (index != -1)
    {
        if (false)
        {
            QFile file("face1.jpg");
            if (file.open(QIODevice::WriteOnly))
            {
                file.write(QByteArray::fromBase64(m_jpg));
                file.close();
            }
        }
        emit textRecv("pic received");
        m_sock->write(QByteArray("success").toBase64() + ",");

        if (time(Q_NULLPTR) < m_recogTime || time(Q_NULLPTR) - m_recogTime > 5)
        {
            m_recog.recognize(QByteArray::fromBase64(m_jpg));
        }

        m_jpg = recvBA.mid(index+1);
    }
}

void FaceRecvCli::onPostOver(const QByteArray &, const QByteArray &data)
{
    QJsonParseError jsonErr;
    QJsonObject jsonObj;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonErr);

    if (jsonErr.error != QJsonParseError::NoError && !jsonDoc.isObject())
    {
        WARNING_PRINT << "recv unkown msg" << data << jsonErr.error;
        return ;
    }

    jsonObj = jsonDoc.object();
    if (m_sock->isValid() && m_sock->isWritable())
    {
        QByteArray tmp = QJsonDocument(jsonObj).toJson(QJsonDocument::Compact).toBase64() + ",";
        emit textRecv(QJsonDocument(jsonObj).toJson(QJsonDocument::Compact));
        m_sock->write(tmp);
        if (jsonObj["is_alarm"].toInt() < 2)
        {
            m_recogTime = time(Q_NULLPTR);
        }
    }
}
